<!--
 * @Author: 可以清心
 * @Description: 
 * @Date: 2022-11-24 11:31:09
 * @LastEditTime: 2023-03-07 13:44:24
-->
<template>
    <div class="form-wrap" v-if="!loading">
        <div class="apaas-login">
            <div class="logo">
                <img src="@/assets/img/logo.png" alt="">
            </div>
            <div class="app-name">
            {{applicationName}}
            </div>
            <router-view></router-view>
        </div>
    </div>
    <div class="loading-wrap" v-else>
        <div class='app-loading' style="color: #005EBA;">
            <div class="loading">
                <div></div>
                <div></div>
                <div></div>
                <div></div>
            </div>
        </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios'
  import qs from 'qs'
  import { RouterView } from 'vue-router';
  import storage from '@/utils/storage'
  // import clearCookie from '@/utils/cookie'
  
  export default {
      name: "JdfForm",
      components: { RouterView },
      data(){
        return {
          applicationName: '京东方低代码平台',
          loading: true
        }
      },
      created(){
        this.jumpWorkBench()
      },
      methods: {
        /**
         * @description: 有token直接跳转工作台
         * @return {void}
         */        
        jumpWorkBench(){
          let storage = localStorage.getItem('__vuex__workbench__local');

          let result;

          try {
            result = JSON.parse(storage);
          } catch (error) {
            console.error('json解析失败')
          }

          if(result && result.authModule && result.authModule.userInfo && result.authModule.userInfo.tenant && result.authModule.userInfo.tenant.id && result.authModule.token){
            window.open(location.origin + '/workbench/' + result.authModule.userInfo.tenant.id + '/workbench', '_self');
          }else{
            let search = qs.parse(location.search.substr(1));
            if(search.type === 'sso'){
              this.ssoLogin();
            }else{
              this.loading = false;
            }
          }
        },
        /**
         * @description: 单点登录逻辑处理
         * @return {*}
         */        
         ssoLogin(){
          let cookies = document.cookie.split("; ");

          let cookieMap = new Map();

          if(cookies.length){
            cookies.forEach(item => {
              let cookie = item.split('=');

              if(cookie.length){
                cookieMap.set(cookie[0], cookie[1])
              }
            })

            if(cookieMap.get('boeType') && cookieMap.get('boeToken')){
              this.getAppUserInfo(cookieMap.get('boeType'), cookieMap.get('boeToken'));
            }else{
              this.loading = false;
            }
          }else{
            this.loading = false;
          }
        },
        /**
         * @description: 获取clientId和clientSecret
         * @return {*}
         */        
        getClientIdAndSecret(){
          let GLOBAL_ENV = window.GLOBAL_ENV;
        
          if(GLOBAL_ENV){
            return {
              clientId: GLOBAL_ENV['BOE_CLIENT_ID'],
              clientSecret: GLOBAL_ENV['BOE_CLIENT_SECRET'],
              authTokenUrl: GLOBAL_ENV['BOE_AUTH_TOKEN_URL']
            }
          }

          return null;
        },
        /**
         * @description: 
         * @param {string} boeType type
         * @param {string} boeToken token
         * @return {void}
         */        
         getAppUserInfo(boeType, boeToken){
          // 使用RuntimeUserService.queryLoginUserVo方法返回 或者 queryLoginUserVoByAccount方法返回 注意返回类型封装成Response格式
          let authInfo = this.getClientIdAndSecret();

          if(authInfo){
            // todo 做请求到后端拿到userInfo
            const {clientId, clientSecret, authTokenUrl} = authInfo;
            axios({
                url: authTokenUrl,
                method: 'post',
                data: {
                    client_id: clientId,
                    client_secret: clientSecret,
                    type: boeType,
                    token: boeToken
                }
            }).then((resp) => {
                const res = resp.data;
                if(res.code === 'ok'){
                    const {setModule} = storage;
                    const {data} = res;
                    setModule(data);
                    // clearCookie();

                    if(location.hostname !== 'localhost'){
                      window.open(location.origin + '/workbench/' + data.tenantId + '/workbench', '_self')
                    }
                }else{
                    if(res.code === 'warning'){
                        this.$message({
                            message: res.message,
                            type: 'warning'
                        });
                    }else{
                        this.$message.error(res.message)
                    }
                    // this.$message.error('单点失败，请检查接口！');
                    this.loading = false;
                }
            }).catch((reason) => {
                console.error(reason);
                this.$message.error(reason?.response?.data?.message);
                this.loading = false;
                // this.$router.push({path: '/417'})
            })
          }else{
            this.$message.error('未配置单点环境变量参数，请检查配置是否完整');
            this.loading = false;
          }
        },
      }
  }
  </script>
  
  <style lang="less">
  .loading-wrap{
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .form-wrap{
    width: 100%;
    height: 100%;
    background-image: url(@/assets/img/background.png);
  }
  .apaas-login {
        
      position: fixed;
      padding: 34px 41px;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 382.5px;
      // height: 370px;
      background-color: #fff;
      box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.10);
      box-sizing: border-box;
  
      .logo {
          // margin-top: 34px;
          text-align: center;
      }
  
      .app-name {
          margin-top: 21.7px;
          margin-bottom: 30px;
          font-family: FZLTHJW--GB1-0;
          font-size: 16px;
          color: #313233;
          text-align: center;
      }
  
      .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner{
        background-color: #005EBA;
        border-color: #005EBA;
      }
  
      .el-button--primary, .el-button--primary:hover, .el-button--primary:focus{
        background-color: #005EBA;
        border-color: #005EBA;
      }
  
      .el-input.is-active .el-input__inner, .el-input__inner:focus{
        border-color: #005EBA;
      }
  }
  </style>
  